
package com.salton123.imagepicker.util;

import android.app.Activity;
import android.os.Build;
import android.view.View;
import android.widget.ImageView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;

import java.lang.ref.WeakReference;


/**
 * Created by liuxun on 2017/12/29.
 */

public class ImageUtils {

    public static void loadImage(ImageView imageView, String imageUrl) {
        final WeakReference<ImageView> imageViewWeakReference = new WeakReference<>(imageView);
        ImageView target = imageViewWeakReference.get();
        if (target != null && target.getContext() != null && !isActivityDestroyed(target)) {
            Glide.with(target.getContext())
                    .load(imageUrl)
                    .into(target);
        }
    }

    public static void loadImage(ImageView imageView, String imageUrl,
                                 int imageWidth, int imageHeight, int defaultIconResId) {
        try {
            final WeakReference<ImageView> imageViewWeakReference = new WeakReference<>(imageView);
            ImageView target = imageViewWeakReference.get();
            if (target != null && target.getContext() != null && !isActivityDestroyed(target)) {
                RequestOptions options = new RequestOptions()
                        .override(imageWidth, imageHeight)
                        .placeholder(defaultIconResId);
                Glide.with(target.getContext())
                        .load(imageUrl)
                        .apply(options)
                        .into(target);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    public static boolean isActivityDestroyed(View target) {
        if (target != null && target.getContext() != null) {
            if (target.getContext() instanceof Activity) {
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1
                        && ((Activity) target.getContext()).isDestroyed()) {
                    return true;
                }
            }
        }
        return false;
    }
}

